import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:${USER}
 * Date:${YEAR}-${MONTH}-${DAY}
 * ${TIME}
 */
public class Main {
    int[] dx={0,0,1,-1};
    int[] dy={1,-1,0,0};
    int m,n;
    public int cutOffTree(List<List<Integer>> forest) {
        m=forest.size();n=forest.get(0).size();
        List<int[]> list=new ArrayList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(forest.get(i).get(j)>1){
                    list.add(new int[]{i,j});
                }
            }
        }
        Collections.sort(list,(a,b)->{
            return forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1]);
        });
        int ret=0;
        int sx=0;int sy=0;
        for (int[] tree:list) {
            int ex=tree[0];int ey=tree[1];
            int step=bfs(forest,sx,sy,ex,ey);
            if(step==-1)return -1;
            ret+=step;
            sx=ex;sy=ey;
        }
        return ret;
    }
    public int bfs(List<List<Integer>> forest,int sx,int sy,int ex,int ey){
        if(sx==ex&&sy==ey){
            return 0;
        }
        boolean[][] vis=new boolean[m][n];
        Queue<int[]> q=new LinkedList<>();
        q.add(new int[]{sx,sy});
        vis[sx][sy]=true;
        int step=0;
        while (!q.isEmpty()){
            step++;
            int size=q.size();
            for (int i=0;i<size;i++){
                int[] tmp=q.poll();
                int a=tmp[0];int b=tmp[1];
                for (int j = 0; j < 4; j++) {
                    int x=a+dx[j];int y=b+dy[j];
                    if(x>=0&&x<m&&y>=0&&y<n&&vis[x][y]==false&&forest.get(x).get(y)>=1){
                        if(x==ex&&y==ey)return step;
                        q.add(new int[]{x,y});
                        vis[x][y]=true;
                    }
                }
            }
        }
        return -1;
    }
}